package com.lancoo.znbkxx.base;

import android.content.Context;
import android.util.Base64;

import com.lancoo.znbkxx.utils.FileUtil;
import com.lancoo.znbkxx.utils.FormatUtil;
import com.lancoo.znbkxx.utils.SharedPreferencesUtils;
import com.google.gson.Gson;


import java.io.File;
import java.io.IOException;

/**
 * Create by TangJun on 2019/2/16
 */
public class PersistentDataCenter {
    private Context context;

    public void init(Context context) {
        SharedPreferencesUtils.getInstance(context);
        this.context = context;
    }

    public AppSettingsBean getAppSettingBeanFromSource() {
        AppSettingsBean appSettingsBean = getObjectFromSharePreference("appSetting", AppSettingsBean.class);
        if (appSettingsBean == null) {
            appSettingsBean = new AppSettingsBean();
        }
        return appSettingsBean;
    }

    public void saveAppSettingBeanFromSource(AppSettingsBean settingsBean) {
        if (settingsBean == null) {
            saveObjectToSharePreference("appSetting", "");
        } else {
            saveObjectToSharePreference("appSetting", settingsBean);
        }

    }

    public void saveObjectToSharePreference(String saveName, Object o) {
        SharedPreferencesUtils.getInstance(context).putStringToShare(saveName, FormatUtil.gson(o));
    }

    public <T> T getObjectFromSharePreference(String saveName, Class<T> tClass) {
        String data = SharedPreferencesUtils.getInstance(context).getStringFromShare(saveName);
        if (data == null || data.length() == 0) {
            return null;
        }
        return new Gson().fromJson(data, tClass);
    }

    public void saveObjectToFile(String saveFile, Object o) {
        File file = new File(saveFile);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileUtil.writeToFile(saveFile, encode(FormatUtil.gson(o)), false);
    }

    public <T> T getObjectFromFile(String saveFile, Class<T> tClass) {
        File file = new File(saveFile);
        if (file.exists()) {
            return new Gson().fromJson(decode(FileUtil.readFromFile(saveFile)), tClass);
        } else {
            return null;
        }
    }

    private String encode(String orig) {
        return new String(Base64.encode(orig.getBytes(), Base64.DEFAULT));
    }

    private String decode(String orig) {
        return new String(Base64.decode(orig, Base64.DEFAULT));

    }

}
